/**
 *
 */
package anysware.gwt.client.ui;

import anysware.gwt.client.ApplicationEvent;
import anysware.gwt.client.EventConstants;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.HistoryListener;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * TODO: doc me
 *
 * @author keke<keke@codehaus.org>
 * @revision $Revision: 106 $
 * @version
 */
public class AnyswareApplicationFrame extends Composite implements
        HistoryListener {
	public static final AnyswareConstants	CONSTANTS	= GWT
	                                                          .create(AnyswareConstants.class);
	private String	                      appToken;
	private final SimplePanel	          mainOut	  = new SimplePanel();

	private final Workspace	              workspace	  = new Workspace();

	public AnyswareApplicationFrame() {
		super();
		final FlowPanel outer = new FlowPanel();
		final FlowPanel header = new FlowPanel();
		header.setStyleName("header");
		final SearchBar searchBar = new SearchBar();
		searchBar.addListener(new SearchController(this));
		header.add(searchBar);
		final Button sourceBtn = new Button(CONSTANTS.sourceButton());
		header.add(sourceBtn);
		sourceBtn.addClickListener(new ClickListener() {

			public void onClick(final Widget sender) {
				new SourceEditorDialog().center();
			}
		});
		outer.add(header);
		outer.add(mainOut);
		initWidget(outer);
		setStyleName("app");
		ensureDebugId("app");
		History.addHistoryListener(this);
		final String hash = Window.Location.getHash();
		if (hash != null) {
			appToken = URL.decode(hash);
		}
	}

	public void fireEvent(final ApplicationEvent event) {
		switch (event.getEventType()) {
		case EventConstants.SEARCH_EVENT:
			break;
		}
	}

	public Workspace getWorkspace() {
		if (mainOut.getWidget() != workspace) {
			mainOut.setWidget(workspace);
		}
		return workspace;
	}

	public void onHistoryChanged(final String historyToken) {
		GWT.log("History: " + historyToken, null);
		appToken = URL.decode(historyToken);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.google.gwt.user.client.ui.Widget#onLoad()
	 */
	@Override
	protected void onLoad() {
		reload(appToken);
	}

	private void reload(final String appToken) {
		// TODO Auto-generated method stub

	}
}
